package com.weibo.log;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.weibo.log.pojo.User;

@Repository("attentionLog")
public class AttentionLog {
	
	@Autowired
	private MongoTemplate mongoTemplate;
	
	private final String COLLECTIONNAME = "attention_log";

	private User user;
	
	public void generateAttentionLog(com.weibo.pojo.User uLogin, Integer initiativeId, Integer passivityId) {
		Integer id = uLogin.getUserId();
		user = findById(id);
		if (user == null) {
			List<Integer> ids = new ArrayList<Integer>();
			ids.add(passivityId);
			user = new User();
			user.setId(initiativeId);
			user.setIds(ids);
			insert(user);
		} else {
			List<Integer> ids = user.getIds();
			ids.add(passivityId);
			update(id, ids);
		}
	}
	
	public User findById(Integer id) {
		return mongoTemplate.findById(id, User.class, COLLECTIONNAME);
	}
	
	public void update(Integer id, List<Integer> ids) {
		mongoTemplate.updateFirst(new Query(Criteria.where("id").is(id)), new Update().set("ids", ids), User.class, COLLECTIONNAME);
	}
	
	public void insert(User user) {
		mongoTemplate.insert(user, COLLECTIONNAME);
	}
}
